package com.cmcc.pcap.packet.util.pfcpUtile;

import com.cmcc.packet.entity.PfcpEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

public class NodeIDUtil implements PfcpTypeUtil{
    private static Logger logger = LogManager.getLogger(NodeIDUtil.class);
    int nodeIdType;
    String ip;
    String fqdn;

    @Override
    public PfcpEntity.InformationElement analysisIe(byte[] sub_payload) {
        PfcpEntity.InformationElement peie = new PfcpEntity.InformationElement();
        peie.setType(((sub_payload[0] & 0xff) << 8) + (sub_payload[1] & 0xff));
        peie.setLength(((sub_payload[2] & 0xff) << 8) + (sub_payload[3] & 0xff));
        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("nodeIdType", String.valueOf((sub_payload[4] & 0xff)));
        switch (dataMap.get("nodeIdType")) {
            case "0":
                if(sub_payload.length >= 5+4) {
                    byte[] ipv4_byte = new byte[4];
                    System.arraycopy(sub_payload, 5, ipv4_byte, 0, 4);
                    try {
                        dataMap.put("ip", String.valueOf(Inet4Address.getByAddress(ipv4_byte)));
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                }else {
                    logger.error("Inadequate TLV length: %d", sub_payload.length);
                }
                break;
            case "1":
                if (sub_payload.length >= 5+16) {
                    byte[] ipv6_byte = new byte[16];
                    System.arraycopy(sub_payload, 5, ipv6_byte, 0, 16);
                    try {
                        dataMap.put("ip", String.valueOf(Inet6Address.getByAddress(ipv6_byte)));
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                }else {
                    logger.error("Inadequate TLV length: %d", sub_payload.length);
                }

                break;
            case "2":
                byte[] fqdn_byte = new byte[4];
                System.arraycopy(sub_payload, 5, fqdn_byte, 0, sub_payload.length-6);
                dataMap.put("fqdn", new String(fqdn_byte));
                break;
        }
        peie.setDataMap(dataMap);
        return peie;
    }

}
